<!DOCTYPE html>
<html class="x-admin-sm">

<head>
    <meta charset="UTF-8">
    <title>欢迎页面-X-admin2.2</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8,target-densitydpi=low-dpi"/>
    <link rel="stylesheet" href="/css/font.css">
    <link rel="stylesheet" href="/css/xadmin.css">
    <link rel="stylesheet" href="/css/uploadImg.css">
    <link rel="stylesheet" href="/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://at.alicdn.com/t/font_1805932_ysrcp4y0uy9.css">
    <script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
    <script src="/lib/layui/layui.js" charset="utf-8"></script>
    <script type="text/javascript" src="/js/xadmin.js"></script>
    <script src="/js/bootstrap.min.js"></script>
    <!-- 让IE8/9支持媒体查询，从而兼容栅格 -->
    <!--[if lt IE 9]>
    <script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
    <script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
    <style>
        .layui-form-item .layui-input-inline {
            width: 250px;
        }
        .layui-form-select dl { max-height:200px; }

    </style>
</head>
<body>
<form class="layui-form " action="">
    <div class="layui-form-item">
        <label class="layui-form-label">商品名称</label>
        <div class="layui-input-inline">
            <input type="text" name="title" required  lay-verify="required" placeholder="请输入商品名称" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">商品价格</label>
        <div class="layui-input-inline">
            <input type="text" name="price" required  lay-verify="required" placeholder="请输入商品价格" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">商品库存</label>
        <div class="layui-input-inline">
            <input type="text" name="num" required  lay-verify="required" placeholder="请输入商品库存" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">商品分类</label>
        <div class="layui-input-inline">
            <label>
                <select name="categoryId" lay-verify="required" id="categorySelect" lay-filter="selectCate">
                    <option value=""></option>
                </select>
            </label>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">存储条件</label>
        <div class="layui-input-block">
            <input type="checkbox" name="storageFac" title="冷冻">
            <input type="checkbox" name="storageFac" title="深冻">
            <input type="checkbox" name="storageFac" title="-18℃">
            <input type="checkbox" name="storageFac" title="0℃">
            <input type="checkbox" name="storageFac" title="常温">
        </div>
    </div>
    <label class="layui-form-label" >详细信息设置</label>
    <div class="layui-form-item">
        <label class="layui-form-label">商品毛重</label>
        <div class="layui-input-inline">
            <input type="text" name="weight" required lay-verify="required" placeholder="请输入毛重/g" autocomplete="off" class="layui-input">
        </div>
        <label class="layui-form-label">商品产地</label>
        <div class="layui-input-inline">
            <input type="text" name="origin" required lay-verify="required" placeholder="请输入产地" autocomplete="off" class="layui-input">
        </div>
        <label class="layui-form-label">商品品种</label>
        <div class="layui-input-inline">
            <input type="text" name="variety" required lay-verify="required" placeholder="请输入品种" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">保质期</label>
        <div class="layui-input-block">
            <input type="radio" name="storage" value="180" title="180天">
            <input type="radio" name="storage" value="360" title="365天">
        </div>
    </div>
    <div class="layui-form-item">
        <div class="upload-content">
            <label class="layui-form-label">上传图片</label>
            <div class="content-img layui-input-block">
                <input type="button" class="layui-btn" value="提交图片" id="uploadImg">
                <ul class="content-img-list"></ul>
                <div class="file">
                    <i class="gcl gcladd"></i>
                    <input type="file" name="file" accept="image/*" id="upload" multiple>
                </div>
            </div>
            <!--放大镜点击放大-->
            <div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">
                <div class="modal-dialog modal-lg" role="document">
                    <div class="modal-content"></div>
                </div>
            </div>
        </div>
    </div>
    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label">商品描述</label>
        <div class="layui-input-block">
            <textarea name="des" placeholder="请输入内容" class="layui-textarea"></textarea>
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="formDemo">立即提交</button>
            <a class="layui-btn layui-btn-danger" href="/cate.html">取消</a>
        </div>
    </div>
</form>
</body>
<script>
    //全局form
    var imgFile = []; //文件流
    var imgSrc = []; //图片路径
    var cateValue=undefined;//目录id
    var imgUrl = [];//服务器返回地址
    var checkBoxVal=[];//保存checkbox中的值
    layui.use(['form','layer'], function(){
        //监听提交
        let form = layui.form;
        let layer = layui.layer;
        form.on('submit(formDemo)', function(data){
            console.log(data);
            let field = data.field;
            //获取图片地址
            let img = $("input[name='file']").data("img");
            if (img == undefined) {
                layer.msg("请先提交图片！");
                return false;
            }
            img = img.toString();
            $.ajax({
                url:"/goods/doSaveGoods",
                type:"POST",
                dataType:"json",
                data:{
                    "title":field.title,
                    "des":field.des,
                    "price":field.price,
                    "weight":field.weight,
                    "origin":field.origin,
                    "num":field.num,
                    "variety":field.variety,
                    "img":img,
                    "categoryId":cateValue,
                    "storage":field.storage,
                    "storageFactor":checkBoxVal.toString()
                },
                success:(result)=>{
                    console.log(result);
                    if (result.status == 200) {
                        layer.confirm(result.msg, {
                            btn: ['确认返回商品页','取消'] //按钮
                        }, function(){
                            window.location.href = "/cate.html";
                        }, function(){
                            layer.msg('也可以这样', {
                                time: 20000, //20s后自动关闭
                                btn: ['明白了', '知道了']
                            });
                        });
                    }else{

                    }
                },
                error:(result)=>{
                    console.log(result);
                }
            });
            return false;
        });
        //获取目录id
        form.on('select(selectCate)',function (data) {
            cateValue=data.value;
            // console.log(value);
        });

        form.on('checkbox',function (data) {
            let name = data.elem.name;
            let title = data.elem.title;
            if (data.elem.checked) {
                checkBoxVal.push(title);
            }else{
                checkBoxVal.splice(checkBoxVal.lastIndexOf(name)-1, 1);
            }
        })
    });
    //下拉框可能会用到 New option
    //这个里面的参数说明 第一个是显示的文本，第二个是value值
    //例如：new Option(item.xm, item.id)第一个参数是下拉列表中显示的值  第二个参数是选中传递给后台的值
    layui.use(['form', 'upload', 'layer'],function(){
        let form = layui.form;
        $.ajax({
            url: '/goods/doFindAllCategory',
            dataType: 'json',
            type: 'get',
            success: function (result) {
                //使用循环遍历，给下拉列表赋值
                $.each(result.data, function (index, value) {
                    if (value.id != 1) {
                        $('#categorySelect').append(new Option(value.name,value.id));// 下拉菜单里添加元素
                    }
                });
                form.render("select");//重新渲染 固定写法
            }
        })
    });
    $(function() {
        // 鼠标经过显示删除按钮
        $('.content-img-list').on('mouseover', '.content-img-list-item', function() {
            $(this).children('div').removeClass('hide');
        });
        // 鼠标离开隐藏删除按钮
        $('.content-img-list').on('mouseleave', '.content-img-list-item', function() {
            $(this).children('div').addClass('hide');
        });
        // 单个图片删除
        $(".content-img-list").on("click", '.content-img-list-item a .gcllajitong', function() {
            var index = $(this).parent().parent().parent().index();
            imgSrc.splice(index, 1);
            imgFile.splice(index, 1);
            var boxId = ".content-img-list";
            addNewContent(boxId);

        });
        $(".content-img-list").on("click", '.content-img-list-item a .gclfangda', function() {
            var index = $(this).parent().parent().parent().index();
            $(".modal-content").html("");

            var bigimg = $(".modal-content").html();
            $(".modal-content").html(bigimg + '<div class="show"><img src="' + imgSrc[index] + '" alt=""><div>');
        });
    });

    //图片上传
    $('#upload').on('change', function(e) {
        var imgSize = this.files[0].size;
        if (imgSize > 1024 * 500 * 1) { //1M
            return alert("上传图片不能超过500KB");
        };
        if (this.files[0].type != 'image/png' && this.files[0].type != 'image/jpeg' && this.files[0].type != 'image/gif') {
            return alert("图片上传格式不正确");
        }

        var imgBox = '.content-img-list';
        var fileList = this.files;
        for (var i = 0; i < fileList.length; i++) {
            var imgSrcI = getObjectURL(fileList[i]);
            imgSrc.push(imgSrcI);
            imgFile.push(fileList[i]);
        }
        addNewContent(imgBox);
        this.value = null; //上传相同图片
    });

    //提交请求
    $('#uploadImg').on('click', function() {
        var formFile = new FormData();
        if (cateValue === "" || cateValue === undefined) {
            alert("必须先选择对应的商品目录！");
            return;
        }
        formFile.append("categoryId", cateValue);
        $.each(imgFile, function(i, file) {
            console.log(file);
            formFile.delete("myFile");
            formFile.append('myFile', file);
            $.ajax({
                url:"/upload/file",
                type:"POST",
                data:formFile,
                async:true,
                cache:false,
                contentType: false,
                processData: false,
                dataType:'json',
                success:function (result) {
                    if (result.error == 0) {
                        let url = result.url;
                        imgUrl.push(url);
                        layui.use('layer',function () {
                            let layer = layui.layer;
                            layer.alert("上传成功！");
                        })
                    }
                }
            })
        });
        $("input[name='file']").data("img", imgUrl);
    });

    //图片展示
    function addNewContent(obj) {
        // console.log(imgSrc)
        $(obj).html("");
        for (var a = 0; a < imgSrc.length; a++) {
            var oldBox = $(obj).html();
            $(obj).html(oldBox + '<li class="content-img-list-item"><img src="' + imgSrc[a] + '" alt="">' +
                '<div class="hide"><a index="' + a + '" class="delete-btn"><i class="gcl gcllajitong"></i></a>' +
                '<a index="' + a + '" class="big-btn" type="button" data-toggle="modal" data-target=".bs-example-modal-lg"><i class="gcl gclfangda"></i></a></div></li>');
        }
    }

    //建立可存取到file的url
    function getObjectURL(file) {
        var url = null;
        if (window.createObjectURL != undefined) { // basic
            url = window.createObjectURL(file);
        } else if (window.URL != undefined) { // mozilla(firefox)
            url = window.URL.createObjectURL(file);
        } else if (window.webkitURL != undefined) { // webkit or chrome
            url = window.webkitURL.createObjectURL(file);
        }
        return url;
    }
</script>
</html>